import { useEffect, useState } from "react";
import { Button, Table, Modal, notification } from "antd";
import { EditOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import axios from "axios";
import { readToken } from "../../../util";
import { useHistory } from "react-router-dom";
/** @import {Role, Right, ReactState, News} from '../../../types' */

function NewsDraft() {
    const history = useHistory();
    /** @type {ReactState<News[]>} */
    const [news, setNews] = useState([]);

    const columns = [
        {
            title: "ID",
            dataIndex: "id"
        },
        {
            title: "新闻标题",
            render: (news) => <a href={"#/news-manage/preview/" + news.id}>{news.title}</a>
        },
        {
            title: "作者",
            dataIndex: "author"
        },
        {
            title: "新闻分类",
            dataIndex: "category",
            render: (c) => c.title
        },
        {
            title: "操作",
            /** @type {(item: News)} */
            render: (news) => (
                <div>
                    <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => handleDelete(news)}></Button>
                    <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => history.push("/news-manage/update/" + news.id)} />
                    <Button shape="circle" icon={<UploadOutlined />} onClick={() => handleAudit(news)}></Button>
                </div>
            )
        }
    ];
    // 拉取数据
    const fetchData = async () => {
        const {username} = readToken();
        let res = await axios.get("/news?_embed=category&auditState=0&username=" + username);
        setNews(res.data);
    };
    useEffect(() => { fetchData(); }, []);

    /** 删除新闻 @type {(item: News) => void} */
    const handleDelete = (news) => {
        Modal.confirm({
            title: "是否删除？",
            onOk: async () => {
                console.log("DeleteNews", news);
                await axios.delete("/news/" + news.id);
                await fetchData();
            }
        });
    };
    
    /** 审核新闻 @type {(news: News) => void} */
    const handleAudit = (news) => {
        axios.patch("/news/" + news.id, {
            auditState: 1
        })
            .then(() => {
                history.push("/audit-manage/list");
                notification.success({description: `可在审核页面中查看刚刚发布的文章。`});
            });
    };

    return (
        <div>
            <Table dataSource={news} columns={columns} rowKey={(item) => item.id }/>
        </div>
    );
}

export default NewsDraft;